'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 建筑
 * @author sundbcn@gmail.com (sun debing)
 */

var _ = require('lodash');
var async = require('async');
var Code = require('../consts/code.js');
var moment = require('moment');
var modelUtil = require('../util/modelUtil');
var mongoConnector = require('../libs/mongodb/mongoConnector');
/* jshint unused:false */
var buildSchema = require('../schemas/buildSchema');
var Build = mongoConnector().model('Build');
var buildType = require('../consts/buildType');
var buildTypeUtil = require('../util/buildTypeUtil.js');
var constantUtil = require('../util/constantUtil.js');
var buildConf = require('../config/buildConf.js');
var activityService = require('../services/activityService');
var actType = require('../consts/activityType.js');
var PlayerManager = require('../libs/playerManager');
var buildService = require('../services/buildService.js');
var unionGroupModel = require('../models/unionGroupModel.js');
var unionHelpModel = require('../models/unionHelpModel.js');
var unionGroupMgr = require('../mgr/unionGroupMgr.js');
var haveHelpMgr = require('../mgr/haveHelpMgr.js');
var haveHelpModel = require('../models/haveHelpModel.js');
/**
 * 根据role_id获取建筑数据
 * @param  {[type]}   role_id [description]
 * @param  {Function} cb      [description]
 * @return {[type]}           [description]
 */
module.exports.getByRoleId = function (role_id, cb) {
    modelUtil.getByRoleId(Build, role_id, function (err, build_model) {
        if (!!err) {
            console.error(err);
            return cb(err);
        }

        cb(null, build_model);
    });
};

/**
 * 获取多个玩家的建筑数据
 */
module.exports.findBuilds = function (where, cb) {
    Build.find(where, cb);
};

/**
 * 刷新数据
 */
module.exports.onRefreshData = function (self, cb) {
    _dealSchedule(self, cb);
};

module.exports.getParadeLv = function (role_id, cb) {
    Build.findOne({
        role_id: role_id
    }, function (err, build_model) {
        if (!!err) {
            return cb(err);
        }
        if (!build_model) {
            return cb(null, 1);
        }
        var parade_build = build_model.getBuildByType(buildType.PARADE);
        if (!!parade_build) {
            return cb(null, parade_build.getLv());
        }
        cb(null, 1);
    });
};

module.exports.getAirshipLv = function (role_id, cb) {
    Build.findOne({
        role_id: role_id
    }, function (err, build_model) {
        if (!!err) {
            return cb(err);
        }
        if (!build_model) {
            return cb(null, 1);
        }
        var airship_build = build_model.getBuildByType(buildType.AIRSHIP);
        if (!!airship_build) {
            return cb(null, airship_build.getLv());
        }
        cb(null, 1);
    });
};

/**
 * 处理建筑排程
 */
var _dealSchedule = function (build_model, callback) {
    // jshint maxstatements:100
    var main_city_changed = false;
    var union_group_model;
    var role_id = build_model.role_id;
    var union_id = 0;
    var build_id;
    var role_model;
    var player_manager = build_model.mgr;
    var build_schedule_list = build_model.getBuildScheduleList();
    var only_item = null;
    if (build_schedule_list.length < 1) {
        return callback();
    }

    var reach_build_end = false;
    var now_time = moment().add(3, 's');
    _.forEach(build_schedule_list, function (build_schedule) {
        if (build_schedule.getEndTime() <= now_time) {
            reach_build_end = true;
            return false;
        }
        return true;
    });

    if (!reach_build_end) {
        return callback();
    }

    if (!player_manager) {
        player_manager = new PlayerManager(role_id);
        player_manager.build = build_model;
    }

    var reach_list = [];
    async.waterfall(
        [
            function (cb) {
                player_manager.getModel(
                    ['role', 'task', 'achieve', 'daily_task', 'accrued'],
                    cb
                );
            },
            function (cb) {
                role_model = player_manager.role;
                union_id = role_model.union_id;

                for (var x = build_schedule_list.length - 1; x >= 0; x--) {
                    var build_schedule = build_schedule_list[x];
                    if (build_schedule.getEndTime() > now_time) {
                        continue;
                    }

                    // 放入已到达结束时间建筑列表中
                    build_id = build_schedule.getBuildId();
                    reach_list.push(build_id);

                    build_model.upgradeBuild(build_id);

                    // 加入任务统计
                    var build_lv = build_model.getBuild(build_id).lv;
                    var build_type_task = parseInt(build_id / 100);
                    buildService.upgradeBuild(player_manager, build_type_task, build_lv);

                    // 判断主城是否升级
                    var build_type = buildTypeUtil.getBuildType(build_id);
                    if (build_type === buildType.NEXUS) {
                        main_city_changed = true;
                    }

                    // 从队列移除
                    build_model.removeBuildSchedule(build_id);
                }
                cb();
            },
            function (cb) {
                // 移除已相应帮助列表和帮助列表
                async.eachSeries(reach_list, function (value, cb1) {
                    _removeHaveHelpAndUnionHelp(role_id, union_id, build_id, cb1);
                }, function (err) {
                    cb();
                });
            },
            function (cb) {
                if (main_city_changed) {
                    // 推送主城升级活动状态
                    activityService.push(build_model.role_id, actType.MAIN_CITY, player_manager);
                    activityService.push(build_model.role_id, actType.NEXUS_LV, player_manager);
                }
                buildService.updateBuildPower(player_manager, false);
                cb();
            }
        ],
        function (err) {
            if (!!err) {
                console.error(err);
                return callback();
            }
            callback();
        }
    );
};

// 移除已帮助列表和帮助列表
var _removeHaveHelpAndUnionHelp = function (role_id, union_id, build_id, callback) {
    if (!union_id) {
        return callback();
    }

    async.waterfall(
        [
            function (cb) {
                _removeUnionHaveHelp(role_id, union_id, build_id, cb);
            },
            function (cb) {
                _removeUnionHelp(role_id, union_id, build_id, cb);
            }
        ],
        function (err) {
            callback(err);
        }
    );
};

// 删除已帮助列表
var _removeUnionHaveHelp = function (role_id, union_id, build_id, cb) {
    var help_info = {
        union_id: union_id,
        role_id: role_id,
        share_id: build_id,
        help_type: 1
    };

    unionHelpModel.findUnionHelpItem(help_info, function (err, have_item) {
        var only_id = have_item._id.toString();
        var have_modify_list = [];
        have_modify_list.push({
            require_role_id: role_id,
            help_type: 1,
            share_id: build_id
        });

        // 推送已帮助列表
        haveHelpMgr.sendHaveHelpChangedMulti(
            union_id, {
                have_list: have_modify_list,
                is_modify: 2
            },
            function (err, fails) {
                if (err) {
                    console.error('send unionGroup message error: %j, fail ids: %j', err, fails);
                    return;
                }
            }
        );
        haveHelpModel.removeMsg('' + only_id, function (err) {});
    });
    cb();
};

// 移除联盟帮助
var _removeUnionHelp = function (role_id, union_id, build_id, cb) {
    var help_info = {
        union_id: union_id,
        role_id: role_id,
        share_id: build_id,
        help_type: 1
    };

    unionHelpModel.removeHelp(help_info, function (err, numberAffected) {
        if (!!err) {
            console.error('err:', err);
            return cb();
        }

        if (numberAffected.n <= 0) {
            // 未申请帮助
            console.warn('not required help msg-------');
            return cb();
        }

        var help_list = {
            is_modify: 2,
            help_list: [help_info]
        };
        unionGroupMgr.sendUnioHelpChangedMulti(
            union_id,
            help_list,
            function (err, fails) {
                if (err) {
                    console.error('send unionGroup message error: %j, fail ids: %j', err, fails);
                    return;
                }
            }
        );

        cb();
    });
};
